#property copyright "Copyright 2025, MetaQuotes Ltd."
#property link      "https://www.metaquotes.net"
#property version   "1.00"
#property indicator_chart_window
#property indicator_buffers 3
#property indicator_plots   1
#property indicator_type1   DRAW_COLOR_LINE
#property indicator_color1  clrDimGray,clrDeepPink,clrDodgerBlue     // 灰色=盘整，粉红=上涨趋势，蓝色=下跌趋势
#property indicator_style1  STYLE_SOLID
#property indicator_width1  2

// 输入参数
input int    InpEMAPeriod = 30;         // EMA周期
input int    InpSmoothPeriod = 3;       // 斜率平滑周期
input double InpSlopeThreshold = 0.05;   // 斜率阈值
input int    InpConfirmBars = 2;        // 确认K线数

// 指标缓冲区
double ExtEMABuffer[];     // EMA值
double ExtColorBuffer[];   // 颜色索引
double ExtSlopeBuffer[];   // 斜率值

// 全局变量
int    g_trend_count = 0;        // 趋势持续计数
int    g_last_trend_type = 0;    // 上一趋势类型 (0=盘整, 1=上涨, 2=下跌)

// 指标句柄
int    handle_ema;  // EMA指标句柄

//+------------------------------------------------------------------+
//| 自定义指标初始化函数                                                |
//+------------------------------------------------------------------+
int OnInit()
{
    // 设置指标缓冲区
    SetIndexBuffer(0, ExtEMABuffer, INDICATOR_DATA);
    SetIndexBuffer(1, ExtColorBuffer, INDICATOR_COLOR_INDEX);
    SetIndexBuffer(2, ExtSlopeBuffer, INDICATOR_CALCULATIONS);
    
    // 设置指标属性
    PlotIndexSetString(0, PLOT_LABEL, "Trend Direction EMA");
    PlotIndexSetInteger(0, PLOT_DRAW_BEGIN, InpEMAPeriod);
    PlotIndexSetDouble(0, PLOT_EMPTY_VALUE, EMPTY_VALUE);
    
    // 创建指标句柄
    handle_ema = iMA(_Symbol, PERIOD_CURRENT, InpEMAPeriod, 0, MODE_EMA, PRICE_CLOSE);
    
    if(handle_ema == INVALID_HANDLE)
    {
        Print("Error creating EMA indicator");
        return(INIT_FAILED);
    }
    
    return(INIT_SUCCEEDED);
}

//+------------------------------------------------------------------+
//| 自定义指标清理函数                                                  |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
    if(handle_ema != INVALID_HANDLE)
        IndicatorRelease(handle_ema);
}

//+------------------------------------------------------------------+
//| 计算EMA斜率                                                         |
//+------------------------------------------------------------------+
double CalculateSlope(const double &ema[], int position, int period)
{
    if(position < period) return 0.0;
    
    // 简化斜率计算，直接使用最近两点
    double slope = (ema[position] - ema[position-1]) / _Point;
    
    return slope;
}

//+------------------------------------------------------------------+
//| 判断趋势状态                                                        |
//+------------------------------------------------------------------+
int DetermineTrendState(double slope, int current_trend)
{
    // 简化的趋势判断逻辑
    if(slope > InpSlopeThreshold) 
    {
        return 1;  // 上涨趋势
    }
    else if(slope < -InpSlopeThreshold) 
    {
        return 2;  // 下跌趋势
    }
    
    // 如果当前已经在趋势中，需要更大的反向移动才会改变状态
    if(current_trend == 1 && slope > -InpSlopeThreshold * 2)
    {
        return 1;  // 保持上涨趋势
    }
    else if(current_trend == 2 && slope < InpSlopeThreshold * 2)
    {
        return 2;  // 保持下跌趋势
    }
    
    return 0;  // 盘整
}

//+------------------------------------------------------------------+
//| 自定义指标迭代函数                                                  |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
                const int prev_calculated,
                const datetime &time[],
                const double &open[],
                const double &high[],
                const double &low[],
                const double &close[],
                const long &tick_volume[],
                const long &volume[],
                const int &spread[])
{
    // 检查数据是否足够
    if(rates_total < InpEMAPeriod + InpSmoothPeriod) return(0);
    
    // 计算起始位置
    int start;
    if(prev_calculated == 0)
    {
        ArrayInitialize(ExtEMABuffer, EMPTY_VALUE);
        ArrayInitialize(ExtColorBuffer, 0);
        ArrayInitialize(ExtSlopeBuffer, 0);
        start = InpEMAPeriod + InpSmoothPeriod;
        g_trend_count = 0;
        g_last_trend_type = 0;
    }
    else
    {
        start = prev_calculated - 1;
    }
    
    // 复制EMA数据
    if(CopyBuffer(handle_ema, 0, 0, rates_total, ExtEMABuffer) <= 0) return(0);
    
    // 主计算循环
    for(int i = start; i < rates_total && !IsStopped(); i++)
    {
        // 计算斜率
        ExtSlopeBuffer[i] = CalculateSlope(ExtEMABuffer, i, InpSmoothPeriod);
        
        // 确定趋势状态
        int new_trend = DetermineTrendState(ExtSlopeBuffer[i], g_last_trend_type);
        
        // 如果趋势状态改变
        if(new_trend != g_last_trend_type)
        {
            g_trend_count = 1;
        }
        else
        {
            g_trend_count++;
        }
        
        // 只有在确认周期后才更新趋势
        if(g_trend_count >= InpConfirmBars)
        {
            ExtColorBuffer[i] = new_trend;
            g_last_trend_type = new_trend;
        }
        else
        {
            ExtColorBuffer[i] = g_last_trend_type;
        }
        
        // 每100个柱子输出一次调试信息
        if(i % 100 == 0)
        {
            Print("Bar: ", i, " Slope: ", ExtSlopeBuffer[i], 
                  " Trend Type: ", g_last_trend_type,
                  " Trend Count: ", g_trend_count);
        }
    }
    
    // 返回计算的K线数量
    return(rates_total);
} 